import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Exam {
    private static final String URL = PropertiesUtils.getProperties("check.url");
    private static StringBuilder sbSave = new StringBuilder();

    private static void saveToSb(String urls) {
        try {
            URL url = new URL(urls);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = httpConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader bufr = new BufferedReader(isr);
                String str;
                while ((str = bufr.readLine()) != null) {
                    sbSave.append(str);
                    sbSave.append("\n");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        saveToSb(URL);
        while (true) {
            if (parse(URL)) {
                sbSave.delete(0,sbSave.length());
                saveToSb(URL);
                EmailSendUtil.sendToMail("63962633@qq.com", "网站已经更新"); //若配置了配置文件，则to和content可设置为null
            }
        }
    }

    private static boolean parse(String urls) {
        boolean isChange = false;
        try {
            URL url = new URL(urls);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = httpConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader bufr = new BufferedReader(isr);
                String str;
                StringBuilder sb = new StringBuilder();
                while ((str = bufr.readLine()) != null) {
                    sb.append(str);
                    sb.append("\n");
                }
                if (!MD5Utils.MD5EncodeUtf8(sb.toString()).equals(MD5Utils.MD5EncodeUtf8(sbSave.toString()))) {
                    System.out.println("网站更新");
                    isChange = true;
                }else{
                    System.out.println("网站尚未更新");
                }
                bufr.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return isChange;
    }
}
